<?php
declare (strict_types=1);

namespace app\common\model;

/**
 * 盟主标志级别
 * Class Video
 * @package app\common\model
 */
class UserLevelFlag extends Base
{
    protected $name = 'user_level_flag';

    /**
     * 盟主级别
     * @param $user
     * @param int $level_id
     * @return false|mixed
     */
    public function flag($user,$level_id = 5)
    {
        $level = array_column(UserLevelFlag::order('id','desc')->select()->toArray(), null, 'id');
        if(!isset($level[$level_id])){
            return $this->decline($user, $level_id);
        }
        $direct_count = $level[$level_id]['direct_count'];
        $two_team_leaders = $level[$level_id]['two_team_leaders'];
        $other_team_leaders = $level[$level_id]['other_team_leaders'];

        $list = Relation::with('user')->where('first_uid', $user->id)->field('id,uid,algebra')->select();

        $directs = count($list);//直推人数：
        if($directs < $direct_count){
            return $this->decline($user, $level_id);
        }
        $team = 0;
        $two = $other = [];
        foreach ($list as $key=>$val){
            $team_uids = Relation::where('uid', $val->uid)->column('new_uid');
            array_push($team_uids,$val->uid);

            $leaders = User::whereIn('id', $team_uids)->where('level_id', 5)->count();

            if($leaders >= $two_team_leaders){
                array_push($two, $leaders);
                $team ++;
            }else{
                array_push($other, $leaders);
            }
        }

        if($team >= 2){
            if($team > 2){
                asort($two);
                unset($two[0],$two[1]);
                $other = array_merge($other, $two);
            }

            $other_leaders = array_sum($other);
            if($other_leaders >= $other_team_leaders){
                return $this->setFlag($user, $level_id);
            }
        }
        return $this->decline($user, $level_id);
    }

    private function decline($user, $level_id)
    {
        $level_id --;
        if($level_id > 0){
            return $this->flag($user, $level_id);
        }else{
            return false;
        }
    }

    private function setFlag($user, $level_id)
    {
        $user->level_flag_id = $level_id;
        return $user->save();
    }
}
